<template>
    <view class="container">
        <!-- use-chat-record-mode：开启聊天记录模式 -->
		<!-- safe-area-inset-bottom：开启底部安全区域适配 -->
		<!-- bottom-bg-color：设置slot="bottom"容器的背景色，这里设置为和chat-input-bar的背景色一致 -->
        <z-paging
            ref="paging"
            :scroll-with-animation="true"
            :use-chat-record-mode="true"
            :safe-area-inset-bottom="true"
            :auto-to-bottom-when-chat="true"
            :auto-adjust-position-when-chat="true"
            v-model="messageList"
            :auto="false"
            @query="handleLoadMore"
        >
            <template #top>
                <!-- 自定义导航区域开始 -->
                <TridentNavBar leftGotoPath="/pages/index/index">
                    <template #left>
                        <!-- #ifdef MP-ALIPAY -->
                        <i class="iconfont icon-zuojiantou" style="font-size: 36rpx;font-weight: bold"></i>
                        <!-- #else -->
                        <i class="iconfont icon-zuojiantou" style="font-size: 36rpx;"></i>
                        <!-- #endif -->
                    </template>
                    <template #default>
                        <view v-if="query.mode == '1'">
                            <text v-if="friend">{{friend.info.username}}</text>
                            <text v-else><uv-skeletons :loading="true" :skeleton="titleSkeleton" ></uv-skeletons></text>
                        </view>
                        <view v-else>
                            <view v-if="groupChat">{{groupChat.name}} ({{ groupChat.member.length }})</view>
                            <view v-else>
                                <uv-skeletons :loading="true" :skeleton="titleSkeleton" ></uv-skeletons>
                            </view>
                        </view>
                    </template>
                    <template #right >
                        <!-- #ifdef MP-ALIPAY -->
                        <i @click="goto('/pagesChat/info/index?mode=' + query.mode + '&id=' + query.id + '&gid=' + query.gid)" class="iconfont icon-gengduo" style="font-size: 36rpx;font-weight: bold;"></i>
                        <!-- #else -->
                        <i @click="goto('/pagesChat/info/index?mode=' + query.mode + '&id=' + query.id + '&gid=' + query.gid)" class="iconfont icon-gengduo" style="font-size: 36rpx;"></i>
                        <!-- #endif -->
                    </template>
                </TridentNavBar>
                <!-- 自定义导航区域结束 -->
            </template>

            <!-- 空数据 -->
            <template #empty>
                <view class="empty-wrap" v-if="messageList.length == 0">
                    <i class="iconfont icon-kongshuju"></i>
                    <view class="text">暂无聊天信息</view>
                </view>
            </template>

            <!-- 消息区域开始 -->
            <view class="message-wrap">
                <!-- 骨架屏区域开始 -->
                <uv-skeletons :loading="isSkeleton" :skeleton="skeletons" v-for="(item, index) in 4" :key="index"></uv-skeletons>
                <!-- 骨架屏区域结束 -->

                <view v-for="(item, index) in messageList" :key="index">
                    <!-- 接收消息区域开始 -->

                    <!-- 群公告区域开始 -->
                    <template v-if="item.type == 6">
                        <view class="notice-wrap" @click="goto('/pagesGroup/notice/index?gid='+ item.to_uid)">
                            <i class="iconfont icon-tongzhi"></i>
                            <view class="notice-text ellipsis-1">点击查看群公告：{{ item.contents }}</view>
                        </view>
                    </template>
                    <!-- 群公告区域结束 -->
                    <template v-else>
                        <view class="msg-to-wrap" v-if="item.from_uid != userStore.profile.user?.uid">
                            <!-- 头像区域开始 -->
                            <view class="avatar-box" @click="goto('/pagesFriend/detail/index?id=' + friend?.id)">
                                <image :src="item.from_user?.avatar_url ? global.FILE_DOMAIN + item.from_user?.avatar_url : 'src/assets/images/default_avatar.png'"/>
                            </view>
                            <!-- 头像区域结束 -->

                            <!-- 内容区域开始 -->
                            <view class="content-box">
                                <view class="title-panel">
                                    <view class="username" v-if="query.mode == '2'">{{ item.from_user?.username }}</view>
                                    <view class="time">{{ formatTime(item.create_time, 'HH:mm') }}</view>
                                </view>
                                <view class="msg-to-panel">
                                    <!-- 文本消息 -->
                                    <view class="message" v-if="item.type == 1">{{ item.contents }}</view>
                                    
                                    <!-- 图片消息 -->
                                    <view class="message" v-else-if="item.type == 2">
                                        <image
                                            :src="global.FILE_DOMAIN + item.image_url"
                                            @click="handleShowImagePreview(global.FILE_DOMAIN + item.image_url)"
                                        />
                                    </view>

                                    <!-- 位置消息 -->
                                    <view class="message" v-else-if="item.type == 5">
                                        <map
                                            :latitude="Number(item.lat)"
                                            :longitude="Number(item.lng)"
                                            :show-location="false"
                                            style="width: 200rpx; height: 200rpx;"
                                            :markers="[{
                                                id: 1,
                                                latitude: item.lat,
                                                longitude: item.lng,
                                                iconPath: '/static/images/location.png',
                                                width: 34,
                                                height: 30
                                            }]"
                                        ></map>
                                        <view class="masking" @click="handleShowPosition({lat: item.lat as never, lng: item.lng as never, name: item.name, address: item.address})"></view>
                                    </view>
                                </view>
                            </view>
                            <!-- 内容区域结束 -->
                        </view>
                    </template>
                    <!-- 接收息区域结束 -->

                    <!-- 发送消息区域开始 -->
                    <view class="msg-from-wrap" v-if="item.from_uid == userStore.profile.user?.uid">
                        <!-- 内容区域开始 -->
                        <view class="content-from-box">
                            <view class="content-from-panel">
                                <view class="time">{{ formatTime(item.create_time, 'HH:mm') }}</view>
                                <view class="msg-panel">
                                    <view v-if="item.type == 1">{{ item.contents }}</view>
                                    <view v-else-if="item.type == 2">
                                        <image
                                            :src="global.FILE_DOMAIN + item.image_url"
                                            @click="handleShowImagePreview(global.FILE_DOMAIN + item.image_url)"
                                        />
                                    </view>

                                    <!-- 位置消息 -->
                                    <view v-else-if="item.type == 5">
                                        <map
                                            :latitude="Number(item.lat)"
                                            :longitude="Number(item.lng)"
                                            :show-location="false"
                                            style="width: 200rpx; height: 200rpx;"
                                            :markers="[{
                                                id: 1,
                                                latitude: item.lat,
                                                longitude: item.lng,
                                                iconPath: '/static/images/location.png',
                                                width: 34,
                                                height: 30
                                            }]"
                                        ></map>
                                        <view class="masking" @click="handleShowPosition({lat: item.lat as never, lng: item.lng as never, name: item.name, address: item.address})"></view>
                                    </view>
                                </view>
                            </view>
                        </view>
                        <!-- 内容区域结束 -->

                        <!-- 头像区域开始 -->
                        <view class="avatar-from-box" @click="goto('/pages/me/index')">
                            <image :src="userStore.profile.user.avatar_url ? global.FILE_DOMAIN + userStore.profile.user.avatar_url : '/static/images/default_avatar.png'"/>
                        </view>
                        <!-- 头像区域结束 -->
                    </view>
                    <!-- 发送消息区域结束 -->
                </view>

                <!-- 没有更多数据区域 -->
                <view class="no-more-warp" v-if="totalPage < messageListParams.page && totalPage > 1">没有更多数据</view>
            </view>

            <!-- 底部聊天输入框 -->
            <template #bottom>
                <view class="operate-wrap">
                    <!-- 输入框 -->
                    <uni-easyinput
                        v-model="sendMessageParams.contents"
                        focus
                        placeholder="请输入消息"
                        :primaryColor="global.THEME_COLOR"
                    ></uni-easyinput>
                    
                    <!-- 表情按钮 -->
                    <i class="iconfont icon-biaoqing" @click="handleShowEmojiPopup"></i>

                    <!-- 私聊按钮 -->
                    <text class="btn-box" @click="handleSendPrivateChat(1)" v-if="sendMessageParams.contents && query.mode == '1'">发消息</text>

                    <!-- 群聊按钮 -->
                    <text class="btn-box" @click="handleSendGroupChat(1)" v-if="sendMessageParams.contents && query.mode == '2'">发消息</text>

                    <!-- 更多操作按钮 -->
                    <i class="iconfont icon-tianjia" @click="handleShowMoreOperatePopup" v-if="sendMessageParams.contents == ''"></i>
                </view>
            </template>
        </z-paging>
    </view>

    <!-- 表情弹层区域开始 -->
    <uni-popup
        ref="emojiPopup"
        type="bottom"
        background-color="#fff"
    >
        <view class="popup-wrap">
            <view class="title-box">
                <text>选择表情</text>
                <i class="iconfont icon-guanbi" @click="emojiPopup.close()"></i>
            </view>
            <TridentEmoji @swiperChange="onEmojiClick"/>
        </view>
    </uni-popup>
    <!-- 表情弹层区域结束 -->

    <!-- 更多操作弹层区域开始 -->
    <uni-popup
        ref="moreOperatePopup"
        type="bottom"
        background-color="#fff"
    >
        <view class="popup-wrap">
            <view class="title-box">
                <text>更多操作</text>
                <i class="iconfont icon-guanbi" @click="moreOperatePopup.close()"></i>
            </view>
            <view class="operate-box">
                <!-- 上传图片 -->
                <view class="operate-item">
                    <uni-file-picker
                        :limit="1"
                        :del-icon="false"
                        :imageStyles="{
                                width: 100,
                                height: 100,
                                border:{
                                    color:'#bfc1c1',
                                    width:1,
                                    style:'dashed',
                                    radius:'2px'
                                }
                            }"
                        disable-preview
                        file-mediatype="image"
                        @select="handleAfterRead"
                    >
                        <!-- #ifdef MP-ALIPAY -->
                        <view class="operate" style="margin-bottom: 20rpx;">
                            <i class="iconfont icon-tupian"></i>
                            <view class="text">图片</view>
                        </view>
                        <!-- #else -->
                        <view class="operate" style="margin-bottom: 5rpx;">
                            <i class="iconfont icon-tupian"></i>
                            <view class="text">图片</view>
                        </view>
                        <!-- #endif -->
                    </uni-file-picker>
                </view>

                <!-- 上传视频 -->
                <view class="operate-item">
                    <view class="operate" @click="handleVideoAfterRead">
                        <i class="iconfont icon-shipinshangchuan"></i>
                        <view class="text">视频</view>
                    </view>
                </view>

                <!-- 上传音频 -->
                <view class="operate-item">
                    <view class="operate" @click="handleAudioAfterRead">
                        <i class="iconfont icon-yinpinshangchuan"></i>
                        <view class="text">音频</view>
                    </view>
                </view>

                <!-- 位置 -->
                <view class="operate-item" @click="handleSendPosition">
                    <view class="operate">
                        <i class="iconfont icon-dizhi"></i>
                    </view>
                    <view class="text">位置</view>
                </view>
            </view>
        </view>
    </uni-popup>
    <!-- 更多操作弹层区域结束 -->
</template>

<script setup lang="ts">
import { useCommonStore, useUserStore } from '@/stores'
import { goto, wgs84togcj02 } from '@/utils/tools'
import { inject, reactive, ref } from 'vue'
import { reqAddChatTargetAPI } from '@/apis/chatTarget'
import { reqFriendDetailAPI } from '@/apis/friend'
import { reqGroupChatDetailAPI } from '@/apis/groupChat'
import { reqMessageListAPI, reqReadMessageAPI } from '@/apis/message'
import type { MessageListParam, Position, SendMessageParams } from '@/types/chat'
import type { AddChatTargetParams } from '@/types/chatTarget'
import type { Friend } from '@/types/friend'
import type { GroupChat } from '@/types/groupChat'
// npm install lodash-es @types/lodash-es --save
import { cloneDeep } from 'lodash-es'
import { formatTime } from '@/utils/tools'
import dayjs from 'dayjs'
import { onShow } from '@dcloudio/uni-app'
import { messageList, socketIsOpen, websocket } from '@/utils/ws'
import { reqTencentReverseParseAddressAPI } from '@/apis/common'


// --------------- 定义全局变量开始 ---------------
// 获取屏幕边界到安全区域距离
// const { safeAreaInsets } = uni.getSystemInfoSync()

// 全局属性
const global: any = inject('global')

// 用户存储
const userStore = useUserStore()

// 获取页面参数
const query = defineProps({
    "mode": {
        type: String,
        default: '0'
    },
    "id": {
        type: String,
        default: '0'
    },
    "gid": {
        type: String,
        default: '0'
    },
    "is_open": {
        type: String,
        default: '0'
    }
})

// 公共存储
const commonStore = useCommonStore()
// --------------- 定义全局变量结束 ---------------


// 显示
onShow(async() => {

    // 设置当前路由
    commonStore.currentRouteUrl = '/pages/chat/index'

    let params = ref<AddChatTargetParams>()
    if (query.mode == '1') { // 私聊
        await getFriendInfo()
        params.value = {
            mode: 1,
            target_info: {
                target_id: friend.value?.info.uid as never,
                name: friend.value?.info.username as never,
                friend_id: query.id as never,
                avatar_url: friend.value?.info.avatar_url as never
            }
        }
    } else if (query.mode == '2') { // 群聊
        await getGroupChatInfo()
        let groupChatImageUrl = ''
        groupChat.value?.member.forEach((item, key) => {
            if (key < 9) {
                groupChatImageUrl += item.avatar_url + ','
                return
            }
        })

        // 将字符串中最后一个元素","逗号去掉
        groupChatImageUrl = groupChatImageUrl.substring(0, groupChatImageUrl.lastIndexOf(','))

        params.value = {
            mode: 2,
            target_info: {
                target_id: groupChat.value?.id as never,
                name: groupChat.value?.name as never,
                avatar_url: groupChatImageUrl
            }
        }
    }

    if (query.is_open) {
        await reqAddChatTargetAPI(params.value as never)
    }

    // 设置消息列表参数
    if (query.mode == '1') { // 私聊参数
        messageListParams.value.from_uid = userStore.profile.user?.uid
        messageListParams.value.to_uid = friend.value?.info.uid
        messageListParams.value.event_type = 'private-chat'
        messageListParams.value.mode = 1
        messageListParams.value.is_dialogue = 1
    } else if (query.mode == '2') { // 群聊参数
        messageListParams.value.to_uid = groupChat.value?.id
        messageListParams.value.event_type = 'group-chat'
        messageListParams.value.mode = 2
    } else {

    }

    if (query.mode == '1') {
        // 私聊,更新消息为已读
        await reqReadMessageAPI(userStore.profile.user?.uid as never)
    }

    // 获取消息
    await getMessageList()
})



// --------------- 处理发送位置开始 ---------------
// 显示位置
const handleShowPosition = (position: Position) => {
    uni.openLocation({
        latitude: Number(position.lat),
        longitude: Number(position.lng),
        name: position.name,
        address: position.address,
        success: function () {
            console.log('success')
        },
        fail: (err: any) => {
            console.log('err = ', err)
        }
    })
}

// 发送位置
const handleSendPosition = () => {
    console.log('------------- handleSendPosition ---------------');
    uni.showLoading({
        title: '正在定位中...',
        duration: 10000
    })

    // H5端定位
    // #ifdef H5
    uni.getLocation({
        // 高精度定位超时时间(ms)，指定时间内返回最高精度，该值3000ms以上高精度定位才有效果
        // App (3.2.11+)、H5 (3.2.11+)、微信小程序 (基础库 2.9.0+)
        highAccuracyExpireTime: 4000,
        // 开启高精度定位: App (3.4.0+)、H5 (3.4.0+)、微信小程序 (基础库 2.9.0+)
        isHighAccuracy: true,
        success: async (res) => {
            // 关闭定位中
            uni.hideLoading()

            let lng = res.longitude
            let lat = res.latitude
            const gcj02Location = wgs84togcj02(lng, lat)
            if (gcj02Location && gcj02Location.length > 0) {
                lng = gcj02Location[0]
                lat = gcj02Location[1]
            }

            console.log('当前位置的经度：' + lng)
            console.log('当前位置的纬度：' + lat)

            // 逆地址解析: 通过经纬度获取地址信息
            const result = await reqTencentReverseParseAddressAPI({lat, lng})
            console.log('result =', result);
            

            // // 发送消息
            sendMessageParams.value.lat = lat + ''
            sendMessageParams.value.lng = lng + ''
            sendMessageParams.value.name = result.data.name
            sendMessageParams.value.address = result.data.standard_address

            console.log('sendMessageParams = ', sendMessageParams.value);
            

            if (query.mode == '1') { // 私聊
                handleSendPrivateChat(5)
            } else if (query.mode == '2') { // 群聊
                handleSendGroupChat(5)
            }

            moreOperatePopup.value.close()
        },
        fail: function (res) {
            // 关闭定位中
            uni.hideLoading()

            console.log('错误信息：', res)
            uni.showToast({
                icon: 'none',
                title: res.errMsg,
            })
        }
    })
    // #else
    uni.chooseLocation({
        success: function (res) {
            // 关闭定位中
            uni.hideLoading()

            console.log('位置名称：' + res.name);
            console.log('详细地址：' + res.address);
            console.log('纬度：' + res.latitude);
            console.log('经度：' + res.longitude);

            // 发送消息
            sendMessageParams.value.lat = res.latitude + ''
            sendMessageParams.value.lng = res.longitude + ''
            sendMessageParams.value.name = res.name
            sendMessageParams.value.address = res.address

            console.log('sendMessageParams = ', sendMessageParams.value);
            

            if (query.mode == '1') { // 私聊
                handleSendPrivateChat(5)
            } else if (query.mode == '2') { // 群聊
                handleSendGroupChat(5)
            }

            moreOperatePopup.value.close()
        },
        fail: function (res) {
            // 关闭定位中
            uni.hideLoading()
            console.log('打开地图选择位置错误信息：', res)
            
        }
    })
    // #endif
}
// --------------- 处理发送位置结束 ---------------



// --------------- 处理预览图片开始 ---------------
const handleShowImagePreview = (image: string) => {
    uni.previewImage({
		urls: [image]
	})
}
// --------------- 处理预览图片结束 ---------------



// --------------- 处理图片上传开始 ---------------
const handleAfterRead = async (e: any) => {
    console.log('e = ', e);
    const tempFile = e.tempFiles[0]
    console.log('tempFile = ', tempFile);
    
    // 图片类型限制，无需限制
	// const imageTypes = [
	// 	'image/jpg',
	// 	'image/jpeg',
	// 	'image/png',
	// ]

    // let imageType = ''
    // // #ifdef MP-ALIPAY
    // imageType = tempFile.fileType + '/' + tempFile.extname
    // // #else
    // imageType = tempFile.file.fileType
    // // #endif
	// if (!imageTypes.includes(imageType)) {
    //     uni.showToast({
    //         title: '图片类型要求：jpeg、jpg、png',
    //         duration: 1000,
    //         icon: 'none'
    //     })

	// 	return false
	// }

	// 图片大小限制 2M
	if (tempFile.size > 1024 * 1024 * 2) {
        uni.showToast({
            title: '图片大小不能超过2M',
            duration: 1000,
            icon: 'none'
        })

		return false
	}

    uni.showLoading({
        title: '图片上传中...',
        mask: true
    })

    // 上传图片到服务器
    uni.uploadFile({
        url: global.UPLOAD_FILE_API,
        filePath: tempFile.url,
        name: 'image',
        success: (uploadFileRes) => {
            uni.hideLoading()
            // 解析数据
            let result = JSON.parse(uploadFileRes.data)

            if (result.status_code != 200) {
                uni.showToast({
                    icon: 'none',
                    title: '上传失败',
                })

                return false
            }

            // 发送消息
            sendMessageParams.value.image_url = result.data.relative_url
            if (query.mode == '1') {
                handleSendPrivateChat(2)
            } else {
                handleSendGroupChat(2)
            }
            moreOperatePopup.value.close()
        },
        fail: () => {
            uni.hideLoading()
            uni.showToast({
                icon: 'none',
                title: '服务器开小差啦!',
            })
        }
    })
}
// --------------- 处理图片上传结束 ---------------



// --------------- 处理视频上传开始 ---------------
const handleVideoAfterRead = async (e: any) => {
    uni.showToast({
        title: '该功能尚未开通，敬请期待',
        duration: 1000,
        icon: 'none'
    })

    return false
}
// --------------- 处理视频上传结束 ---------------



// --------------- 处理音频上传开始 ---------------
const handleAudioAfterRead = async (e: any) => {
    uni.showToast({
        title: '该功能尚未开通，敬请期待',
        duration: 1000,
        icon: 'none'
    })
    
    return false
}
// --------------- 处理音频上传结束 ---------------



// --------------- 处理发送消息开始 ---------------
// 发消息参数
const sendMessageParams = ref<SendMessageParams>({
    id: 0,
    from_uid: userStore.profile.user?.uid as never,
    from_user: {
        uid: userStore.profile.user?.uid as never,
        username: userStore.profile.user?.username as never,
        mobile: userStore.profile.user?.mobile as never,
        avatar_url: userStore.profile.user?.avatar_url as never
    },
    to_uid: 0,
    mode: 1,
    event_type: '',
    type: 1,
    contents: '',
    image_url: '',
    voice_url: '',
    video_url: '',
    is_read: 0,
    status: 1,
    create_time: ''
});

// 处理发送私聊消息
const handleSendPrivateChat = async (type: number) => {
    console.log('-------------- 私聊 --------------');
    
    if (type == 1 && sendMessageParams.value.contents == '') {
        uni.showToast({
            title: '请输入消息',
            duration: 1000,
            icon: 'none'
        })

        return false
    }

    // 设置消息接受者
    sendMessageParams.value.to_uid = friend.value?.info.uid as never
    sendMessageParams.value.to_user = {
        uid: friend.value?.info.uid as never,
        username: friend.value?.info.username + '',
        mobile: friend.value?.info.mobile + '',
        avatar_url: friend.value?.info.avatar_url
    }

    // 设置消息事件
    sendMessageParams.value.event_type = 'private-chat'

    // 设置消息模式：1-私聊，2-群聊，3-通知
    sendMessageParams.value.mode = 1

    // 设置消息类型：1-文本，2-图片，3-语音，4-视频，5-表情
    sendMessageParams.value.type = type

    // 设置创建时间
    sendMessageParams.value.create_time = dayjs().format('YYYY-MM-DD HH:mm:ss')

    console.log('发送消息数据 = ', sendMessageParams.value)

    // 打开加载中提示
    // loadingInstance.value.open()
    const message = cloneDeep(sendMessageParams.value)

    // 添加消息到消息列表
    messageList.value.unshift(message)
    
    // 发送消息
    // #ifdef MP-ALIPAY
    if (socketIsOpen) {
        uni.sendSocketMessage({data: JSON.stringify(message)})
    }
    // #else
    websocket.value?.send({data: JSON.stringify(message)})
    // #endif

    // 清空消息内容
    sendMessageParams.value.contents = ''
}

// 处理发送群聊消息
const handleSendGroupChat = async (type: number) => {
    if (type == 1 && sendMessageParams.value.contents == '') {
        uni.showToast({
            title: '请输入消息',
            duration: 1000,
            icon: 'none'
        })
        return false
    }

    // 设置消息接受者
    sendMessageParams.value.to_uid = groupChat.value?.id as never

    // 设置消息事件
    sendMessageParams.value.event_type = 'group-chat'

    // 设置消息模式：1-私聊，2-群聊，3-通知
    sendMessageParams.value.mode = 2

    // 设置消息类型：1-文本，2-图片，3-语音，4-视频，5-表情
    sendMessageParams.value.type = type

    // 设置创建时间
    sendMessageParams.value.create_time = dayjs().format('YYYY-MM-DD HH:mm:ss')

    console.log('发送消息数据 = ', sendMessageParams.value)

    // loadingInstance.value.open()

    const message = cloneDeep(sendMessageParams.value)

    // 添加消息到消息列表
    messageList.value.unshift(message)

    console.log('message =', message)

    // 发送消息
    // #ifdef MP-ALIPAY
    if (socketIsOpen) {
        uni.sendSocketMessage({data: JSON.stringify(message)})
    }
    // #else
    websocket.value?.send({data: JSON.stringify(message)})
    // #endif

    // 清空消息内容
    sendMessageParams.value.contents = ''
}
// --------------- 处理发送消息结束 ---------------



// --------------- 处理加载更多开始 ---------------
const handleLoadMore = async (pageNo: number, pageSize: number) => {
    messageListParams.value.page = pageNo
    await getMessageList()
}
// --------------- 处理加载更多结束 ---------------



// --------------- 处理消息列表开始 ---------------
const paging = ref()

// 总条数
const total = ref<number>(0)

// 总页数
const totalPage = ref<number>(0)

// 消息列表参数
const messageListParams = ref<MessageListParam>({
    from_uid: 0,
    to_uid: 0,
    mode: 0,
    event_type: '',
    is_dialogue: 0,
    type: 0,
    page: 1,
    page_size: 10,
    sort_field: 'create_time',
    sort_type: 'desc'
})

// 获取消息列表
const getMessageList = async () => {
    if (messageListParams.value.page == 1) {
        // 显示骨架屏    
        isSkeleton.value = true
    }

    const result = await reqMessageListAPI(messageListParams.value)
    const messages = result.data.messages
    messageList.value.push(...messages)
    paging.value.complete(messages);
    
    total.value = result.data.total
    totalPage.value = result.data.total_page

    // 关闭骨架屏
    isSkeleton.value = false
}
// --------------- 处理消息列表结束 ---------------



// --------------- 处理好友信息开始 ---------------
// 获取好友信息
const friend = ref<Friend>()

// 获取好友信息
const getFriendInfo = async () => {
    const result = await reqFriendDetailAPI(query.id as never)
    friend.value = result.data
}
// --------------- 处理好友信息开始 ---------------



// --------------- 处理群聊信息开始 ---------------
// 群聊信息
const groupChat = ref<GroupChat>()

// 获取群聊信息
const getGroupChatInfo = async () => {
    const result = await reqGroupChatDetailAPI(query.gid as never)
    groupChat.value = result.data
}
// --------------- 处理群聊信息结束 ---------------



// --------------- 处理更多操作开始 ---------------
const moreOperatePopup = ref()

// 显示选择更多操作弹层
const handleShowMoreOperatePopup = () => {
    sendMessageParams.value.image_url = ''
    sendMessageParams.value.video_url = ''
    sendMessageParams.value.voice_url = ''

    moreOperatePopup.value.open()
}
// --------------- 处理更多操作结束 ---------------



// --------------- 处理表情操作开始 ---------------
const emojiPopup = ref()

// 显示表情弹层
const handleShowEmojiPopup = async () => {
    emojiPopup.value.open()
}

// 选择表情
const onEmojiClick = (emoji: string) => {
    sendMessageParams.value.contents += emoji
    emojiPopup.value.close()
}
// --------------- 处理表情操作结束 ---------------



// --------------- 定义骨架变量开始 ---------------
// 定义是否显示骨架
const isSkeleton = ref(false)

// 定义骨架参数
const skeletons = reactive([
    // 发送者
    {
        type: 'flex',
        num: 1,
        style: 'padding: 15rpx 0 15rpx 0;align-items: center;justify-content: flex-end;',
        children: [
            {
                type: 'custom',
                num: 2,
                style: ['width: 200rpx;height: 80rpx;', 'width: 200rpx;height: 30rpx;']
            },

            // 头像区域
            {
                type: 'custom',
                num: 1,
                style: 'width: 100rpx;height: 100rpx;border-radius: 50rpx;margin-left: 20rpx;'
            },
        ]
    },

    30,

    // 接受者
    {
        type: 'flex',
        num: 1,
        style: 'padding: 15rpx 0 15rpx 0;align-items: center;',
        children: [
            // 图片区域
            {
            type: 'custom',
            num: 1,
            style: 'width: 100rpx;height: 100rpx;border-radius: 50rpx;margin-right: 20rpx;'
            },

            {
            type: 'custom',
            num: 2,
            style: ['width: 200rpx;height: 80rpx;', 'width: 100rpx;height: 30rpx;']
            }
        ]
    },
    30
])

// 导航栏骨架参数
const titleSkeleton = ref([
    {
        type: 'line',
        num: 1,
        gap: '20rpx',
        style: ['width: 200rpx;'],
    }
])
// --------------- 定义骨架变量结束 ---------------
</script>

<style scoped lang="scss">
::v-deep .icon-add {
    display: none;
}
.container {
    // 消息区域开始
    .message-wrap {
        padding: 0 30rpx;
        // 群公告区域开始
        .notice-wrap {
            transform: scaleY(-1);
            background-color: #e9e9e9;
            display: flex;
            margin: 50rpx 0;
            padding: 0 20rpx;
            border-radius: 5px;
            height: 80rpx;
            line-height: 80rpx;
            .icon-tongzhi {
                color: $uni-color-primary;
            }
            .notice-text {
                width: 640rpx;
                margin-left: 10rpx;
                color: #696868;
                font-size: 24rpx;
            }
        }
        // 群公告区域结束

        // 发消息区域开始
        .msg-to-wrap {
            transform: scaleY(-1);
            margin: 50rpx 0;
            display: flex;
            .avatar-box {
                margin-right: 20rpx;
                border: 2rpx solid #d3f4ed;
                width: 100rpx;
                height: 100rpx;
                display: flex;
                align-items: center;
                justify-content: center;
                border-radius: 100%;
                overflow: hidden;

                image {
                    width: 100rpx;
                    height: 100rpx;
                }
            }
            .content-box {
                flex: 1;
                image {
                    width: 200rpx;
                    height: 200rpx;
                    border-radius: 4rpx;
                }

                .title-panel {
                    display: flex;
                    align-items: center;
                    .username {
                        font-weight: bold;
                        font-size: 26rpx;
                    }
                    .time {
                        color: gainsboro;
                        font-size: 28rpx;
                        margin-left: 10rpx;
                    }
                    padding-bottom: 20rpx;
                }

                .msg-to-panel {
                    display: flex;
                    .message {
                        background-color: #fff;
                        padding: 20rpx;
                        max-width: 560rpx;
                        border-radius: 16rpx;
                    }
                    position: relative;

                    // 蒙版
                    .masking {
                        background-color: rgba(255, 255, 255, 0);
                        position: absolute;
                        left: 0;
                        top: 0;
                        width: 200rpx;
                        height: 200rpx;
                        border-radius: 20rpx;
                    }
                }
            }
        }
        // 发消息区域结束

        // 接收消息区域开始
        .msg-from-wrap {
            transform: scaleY(-1);
            margin: 80rpx 0;
            display: flex;
            justify-content: flex-end;
            .content-from-box {
                display: flex;
                justify-content: flex-end;
                .content-from-panel {
                    .time {
                        display: flex;
                        justify-content: flex-end;
                        color: gainsboro;
                        font-size: 28rpx;
                        padding-bottom: 30rpx;
                    }

                    img {
                        width: 100px;
                        height: 100px;
                        border-radius: 5px;
                    }

                    .msg-panel {
                        background-color: $uni-color-primary;
                        padding: 10px;
                        line-height: 22px;
                        max-width: 300px;
                        border-radius: 10px;
                        color: #fff;
                        position: relative;
                        image {
                            width: 200rpx;
                            height: 200rpx;
                            border-radius: 10rpx;
                        }
                        .masking {
                            background-color: rgba(255, 255, 255, 0);
                            position: absolute;
                            left: 0;
                            top: 0;
                            width: 100px;
                            height: 100px;
                            border-radius: 10px;
                        }
                    }
                }
            }
            .avatar-from-box {
                margin-left: 10rpx;
                border: 2rpx solid $uni-color-primary;
                width: 100rpx;
                height: 100rpx;
                display: flex;
                align-items: center;
                justify-content: center;
                border-radius: 100%;
                overflow: hidden;
                image {
                    width: 100rpx;
                    height: 100rpx;
                }
            }
        }
        // 接收消息区域结束
    }
    // 消息区域结束

    // 操作区域开始
    .operate-wrap {
        display: flex;
        align-items: center;
        justify-content: space-between;
        background-color: #fff;
        border-top: 2rpx solid #dadada;
        padding: 4rpx 10rpx;
        .btn-box {
            background-color: $uni-color-primary;
            color: #fff;
            padding: 10rpx 15rpx;
            border-radius: 4rpx;
        }
        .icon-biaoqing, .icon-tianjia {
            font-size: 38px;
            color: $uni-color-primary;
        }
        .icon-biaoqing {
            margin: 0 10rpx;
        }
    }
    // 操作区域结束

    // 没有更多区域开始
    .no-more-warp {
        transform: scaleY(-1);
        display: flex;
        justify-content: center;
        background-color: #dadada;
        // color: #fff;
        padding: 15rpx 0;
    }

    // 空数据区域开始
    .empty-wrap {
        display: flex;
        flex-direction: column;
        color: #b2b3b3;
        .icon-kongshuju {
            font-size: 200rpx;
        }
        .text {
            margin-top: 20rpx;
            color: #b2b3b3;
        }
    }
    // 空数据区域结束
}

// 弹层区域开始
.popup-wrap {
    padding-bottom: 40rpx;

    // 标题区域
    .title-box {
        display: flex;
        align-items: center;
        font-size: 32rpx;
        font-weight: bold;
        justify-content: center;
        height: 80rpx;
        color: $uni-color-primary;
        position: relative;
        border-bottom: 2rpx solid #e3e2e2;
        .icon-guanbi {
            font-size: 44rpx;
            color: #8e8c8c;
            position: absolute;
            right: 20rpx;
        }
    }

    .operate-box {
        padding-top: 20rpx;
        display: flex;
        justify-content: space-evenly;

        .operate-item {
            display: flex;
            justify-content: center;
            align-items: center;
            flex-direction: column;
            width: 160rpx;
            height: 160rpx;
            background-color: #bfc1c1;
            margin-top: 20rpx;
            border-radius: 16rpx;
            overflow: hidden;
            .operate {
                // margin-bottom: 20rpx;
                .iconfont {
                    font-size: 60rpx;
                    color: #fff;
                }
            }
            .text {
                bottom: 180rpx;
                color: #fff;
                font-size: 28rpx;
            }
        }
    }
}
</style>